import * as React from "react";
import { Select } from "antd";
import { MyAxios } from "../../../../../common/config/http";
import { IOwnerSelect } from "../../interfaces";
import { Reducers } from "../../../../../App";
import { IReducerState_TableFilter } from "../../store/reducer";
import { Dispatch } from "redux";
import { setTableFilterAct } from "../../store/actions";
import { connect } from "react-redux";
const { Option } = Select;

interface IStateProps {
  filter: IReducerState_TableFilter;
}

interface IDispatchProps {
  setFilter: (filter: IReducerState_TableFilter) => void;
}

type IProps = IStateProps & IDispatchProps;

const SelectOwner: React.FC<IProps> = props => {
  const { filter, setFilter } = props;

  const [ownerList, setOwnerList] = React.useState<Array<IOwnerSelect>>([]);
  function getOwnerList(username: string) {
    MyAxios.axios
      .post(
        "user/select/query",
        { username },
        { headers: { ...MyAxios.getToken() } }
      )
      .then(res => {
        setOwnerList(res.data);
      });
  }

  return (
    <Select
      allowClear
      style={{ width: 200 }}
      value={filter.ownerId}
      onChange={(v: number) => {
        setFilter({ ...filter, ownerId: v });
      }}
      showSearch
      placeholder="搜索用户"
      defaultActiveFirstOption={false}
      showArrow={false}
      filterOption={false}
      onSearch={v => {
        if (v) {
          getOwnerList(v);
        } else {
          setOwnerList([]);
        }
      }}
      notFoundContent={null}
    >
      {ownerList.map(item => (
        <Option key={item.id} value={item.id}>
          {item.username}
        </Option>
      ))}
    </Select>
  );
};

function mapStateToProps(state: Reducers): IStateProps {
  const reducer = state.manageOrderReducer;
  return {
    filter: reducer.table_filter
  };
}

function mapDispatchToProps(dispatch: Dispatch): IDispatchProps {
  return {
    setFilter(filter: IReducerState_TableFilter) {
      const action = setTableFilterAct(filter);
      dispatch(action);
    }
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(SelectOwner);
